
/* ______________________________________________________________________

	Thread Class
	This class creates a Timer based thread for JS code execution.

	License: MIT License

	Vaca Framework
	http://vaca-framework.googlecode.com/
   ______________________________________________________________________
*/

Vaca.Controllers.ThreadCount = 0;

Vaca.Controllers.Thread = new Class({
	ClassName: 'Thread',
	Extends: Vaca.BaseObject,
	Implements: [Options, Events],

	threadId: '',
	timer: null,

	options: {
		interval: 1000,
		autostart: false
	},
		
	initialize: function(options) {
		this.setOptions(options);
		this._generateId();
		if (this.options.autostart) this.start();
	},

	start: function() {
		this._setTimer();
		this.fireEvent('start', [this]);
	},

	stop: function() {
		this._stopTimer();
		this.fireEvent('stop', [this]);
	},

	setInterval: function(time) {
		this.options.interval = time;
	},


	/* Private functions */

	_generateId: function() {
		this.threadId = 'VacaThread-' + ++Vaca.ThreadCount;
	},

	_setTimer: function() {
		if (this.timer == null) {
			this.timer = setInterval(function(){
				this._execute(this);
			}.bind(this), this.options.interval);
		}
	},

	_stopTimer: function() {
		if (this.timer != null) {
			clearInterval(this.timer);
			this.timer = null;
		}
	},

	/* This function is called from a timer which doesn't know about 'this' */
	_execute: function(self) {
		self._stopTimer();
		self.beforeExecute();
		self.execute();
		self.afterExecute();
		self._setTimer();
	},

	beforeExecute: function() {
		// console.log(self.threadId + ": executing...");
	},

	execute: function() {
		this.fireEvent('execute', [this]);
	},

	afterExecute: function() {
		// console.log(self.threadId + ": done.");
	}
	
});
